package com.hsd.znsh.controller.manager;

import com.hsd.znsh.code.ValidateCodeProcessor;
import com.hsd.znsh.code.ValidateCodeProcessorHolder;
import com.hsd.znsh.entity.Function;
import com.hsd.znsh.entity.User;
import com.hsd.znsh.enums.DeletedStatusEnum;
import com.hsd.znsh.enums.UserRoleEnum;
import com.hsd.znsh.pojo.input.UserInfoInput;
import com.hsd.znsh.pojo.output.*;
import com.hsd.znsh.pojo.query.FarmQuery;
import com.hsd.znsh.pojo.query.OpinionQuery;
import com.hsd.znsh.pojo.query.UserQuery;
import com.hsd.znsh.repository.FunctionRepository;
import com.hsd.znsh.repository.RoleFunctionRepository;
import com.hsd.znsh.repository.UserRepository;
import com.hsd.znsh.repository.UserRoleRepository;
import com.hsd.znsh.service.CommonService;
import com.hsd.znsh.service.FarmService;
import com.hsd.znsh.service.UserService;
import com.hsd.znsh.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;

/*
 * @auther: wangjiacai
 *
 * @create: 2018-04-23 11:25:01
 */
@RequestMapping("/manager/user")
@Controller
public class ManagerUserController {

    @Autowired
    private CommonService commonService;

    @Autowired
    private UserService userService;

    @Autowired
    private FarmService farmService;

    @Autowired
    private ValidateCodeProcessorHolder validateCodeProcessorHolder;

    @Autowired
    private UserRoleRepository userRoleRepository;

    @Autowired
    private RoleFunctionRepository roleFunctionRepository;

    @Autowired
    private FunctionRepository functionRepository;

    @GetMapping("/login")
    public String toLogin(){
        return "manager/login";
    }

    @RequestMapping("/main")
    public String toMain(HttpServletRequest request){
        request.setAttribute("username",SecurityUtil.getUsername());
        return "manager/main";
    }

    @PostMapping("/sendSmsCode")
    public void sendSmsCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ValidateCodeProcessor validateCodeProcessor=validateCodeProcessorHolder.findValidateCodeProcessor("sms");
        validateCodeProcessor.create(new ServletWebRequest(request, response));
    }

    @GetMapping("/getUserRole")
    @ResponseBody
    public ResultVO getUserRole(){
        return ResultVOUtil.success(commonService.getUserRole(SecurityUtil.getUser()));
    }

    @GetMapping("/getUserRoleList")
    @ResponseBody
    public ResultVO getUserRoleList(){
        List<Map> list=userService.getManagerUserRoleList();;
        return ResultVOUtil.success(list);
    }

    @GetMapping("/getUserList")
    @ResponseBody
    public ResultVO getUserListTotalPages(Integer size, UserQuery userQuery){
        long totalNum;
        if(SecurityUtil.hasRole("ROLE_ROOT")){
            totalNum=userService.getUserListTotalPages(userQuery,null);
        }else{
            totalNum=userService.getUserListTotalPages(userQuery,SecurityUtil.getUserId());
        }
        return ResultVOUtil.success((long)Math.ceil(totalNum/(double)size));
    }

    @PostMapping("/getUserList")
    @ResponseBody
    public ResultVO getUserList(@PageableDefault( sort = "updateDateTime",direction = Sort.Direction.DESC) Pageable pageable, UserQuery userQuery){
        List<UserVO> list;
        if(SecurityUtil.hasRole("ROLE_ROOT")){
            list=userService.getUserList(pageable,userQuery,null);
        }else{
            list=userService.getUserList(pageable,userQuery,SecurityUtil.getUserId());
        }
        return ResultVOUtil.success(list);
    }

    @GetMapping("/getUserInfo")
    @ResponseBody
    public ResultVO getUserInfo(Integer id){
        UserInfoVO userInfoVO=userService.getUserInfo(id);
        return ResultVOUtil.success(userInfoVO);
    }

    @PostMapping("/updateUserInfo")
    @ResponseBody
    public ResultVO updateUserInfo(@Valid UserInfoInput userInfoInput, BindingResult bindingResult){
        ValidatorUtil.valid(bindingResult);
        if(userInfoInput.getId()==null){
            userService.addUserInfo(userInfoInput);
            return ResultVOUtil.success("添加成功");
        }else{
            userService.updateUserInfo(userInfoInput);
            return ResultVOUtil.success("修改成功");
        }
    }

    @PostMapping("/deleteUser")
    @ResponseBody
    public ResultVO deleteUser(Integer id){
        userService.deleteUser(id);
        return ResultVOUtil.success("删除成功");
    }

    @GetMapping("/downloadUserVIP")
    @ResponseBody
    public void downloadUserVIP(HttpServletResponse response) throws IOException {
        UserQuery userQuery=new UserQuery();
        userQuery.setUserType(UserRoleEnum.VIP.getCode());
        userQuery.setDeleted(DeletedStatusEnum.NOT_DELETED.getCode());
        List<UserVO> list=userService.getUserList(userQuery);
        ExcelUtil.downLoadXls("VIP用户.xls","VIP用户","VIP",list,UserVO.class,response);
    }

    @GetMapping("/farmExport")
    @ResponseBody
    public void farmExport(FarmQuery farmQuery,HttpServletResponse response)throws IOException {
        List<FarmVO> list;
        if(SecurityUtil.hasRole("ROLE_ROOT")){
            list=farmService.getFarmList(farmQuery,null);
        }else list=farmService.getFarmList(farmQuery,SecurityUtil.getUserId());
        ExcelUtil.downLoadXls("农事记录.xls","农事记录","农事",list,FarmVO.class,response);
    }

    @GetMapping("/getFunctionList")
    @ResponseBody
    public List<Function> getFunctionList(){
        List<Integer> roleIds=userRoleRepository.findRoleIdListByUserId(SecurityUtil.getUserId());
        List<Integer> functionIds=roleFunctionRepository.findFunctionIdListByRoleIdIn(roleIds);
        List<Function> list=functionRepository.findByIdInOrderByBhAsc(functionIds);
        return list;
    }
}
